/*
 * TesterLoadJar.java	 
 *
 * Copyright 2011 Universidad Francisco de Paula Santander (UFPS).
 * Todos los Derechos Reservados.
 * Creado el 07/10/11, 11:23:38 AM
 */
package com.ufps.cuatro.util.generadores;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.ufps.cuatro.modelo.analizador.CargadorClases;
import com.ufps.cuatro.modelo.analizador.UtilAnalizador;
import com.ufps.cuatro.util.Utileria;

/**
 * <i><b>TesterLoadJar:</b></i><p>Evaluador de Carga del Modelo Analizado.</p>
 * <p>Permite evaluar referencias externas antes de realizar la carga de jar, con el
 * fin de solucionarlas para evitar errores, posteriores.</p>
 * 
 * @author Carlos A. Torres C. - Dolly E. Guerrero. <https://code.google.com/p/tesis4dor/>
 * @version 1.0 07/10/11
 */
public class TesterLoadJar {
    
    public final static int PROCESS_OK = 0;
    public final static int PROCESS_CANCEL = 1;
    public final static int PROCESS_ERROR = -1;
    public final static int FRECUENCE_TIMER = 100; 
    private File objFile;
    private long lengthOfTask;
    private long current = 0;
    private String statMessage;    
    private int action = PROCESS_CANCEL;

    /**
     * 
     * @param objFile
     */
    public TesterLoadJar(File objFile) {
        this.objFile = objFile;
        this.lengthOfTask = Utileria.objFileJar.length();        
    }

    /**
     * 
     * @return
     */
    public long getCurrent() {
        return current;
    }

    /**
     * 
     * @return
     */
    public long getLengthOfTask() {
        return lengthOfTask;
    }

    /**
     * 
     * @return
     */
    public String getStatMessage() {
        return statMessage;
    }
    
    /**
     * 
     */
    public void stop() {
        current = lengthOfTask;
    }

    //called from ProgressBarDemo to find out if the task has completed
    /**
     * 
     * @return
     */
    public boolean done() {
        return (current >= lengthOfTask) ? true : false;            
    }
    
    //called from ProgressBarDemo to start the task
    /**
     * 
     */
    public void go() {
        current = 0;
        final com.ufps.cuatro.util.generadores.worker.SwingWorker worker = new com.ufps.cuatro.util.generadores.worker.SwingWorker() {
            public Object construct() {
                return new ActualTask();
            }
        };
    }
    
    //the actual long running task, this runs in a SwingWorker thread
    class ActualTask {
        JarInputStream jarInput = null;                            
        JarEntry jarEntry = null;
        ActualTask () {
            //fake a long task,
            //make a random amount of progress every second                                    
            if(analyze()){
                action = PROCESS_OK; 
            }
            else{
                action = PROCESS_ERROR;
            }
            current = lengthOfTask;            
        }
        
        private boolean analyze(){
            try { 
                boolean retorno = true;
                CargadorClases mc = new CargadorClases();
                mc.addArchivo(objFile);                
                System.out.println("Iniciando Preanalisis.");                                
                jarInput = new java.util.jar.JarInputStream(new FileInputStream(Utileria.objFileJar));                                                
                while ((jarEntry = jarInput.getNextJarEntry()) != null) {                    
                    String strClase = jarEntry.getName();                    
                    current += jarEntry.getSize();                    
                    if(strClase.endsWith(".class")){
                        strClase = strClase.replace('/', '.');
                        strClase = UtilAnalizador.eliminarExtensionBack(strClase);
                        try{
                            if (!UtilAnalizador.estaRegistradaEnElClassPath(strClase)) {                                
                                statMessage = "<b><font color=#990000>Analizando Clase: " + strClase + " Size: " + current + " de: " + lengthOfTask+ "</font></b>";
                                retorno = false;
                            }
                            else{
                                statMessage = "<b><font color=#669933>Analizando Clase: " + strClase + " Size: " + current + " de: " + lengthOfTask + "</font></b>";
                            }
                        }catch(java.lang.NoClassDefFoundError ex){                            
                            statMessage = "<b><font color=#990000>Clase sin Ref: " + ex.getMessage() + " Size: " + current + " de: " + lengthOfTask + "</font></b>";
                            retorno = false;
                        }
                    }  
                    else{
                        statMessage = "Ignorando Recurso: " + strClase + " Size: " + current + " de: " + lengthOfTask;
                    }
                    try {
                        Thread.sleep(FRECUENCE_TIMER); //sleep for a second
                    } catch (InterruptedException ex) {
                        Logger.getLogger(TesterLoadJar.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                return retorno;
            } catch (IOException ex) {
                Logger.getLogger(TesterLoadJar.class.getName()).log(Level.SEVERE, null, ex);
            } catch (NoSuchMethodException ex) {
                Logger.getLogger(TesterLoadJar.class.getName()).log(Level.SEVERE, null, ex);
            }
            return false;
        }
    }    

    public int getAction() {
        return action;
    }

    public void setAction(int action) {
        this.action = action;
    }
}
